#!/bin/bash

APP_HOME="/data/server"
APP_NAME="auto"
PID_FILE="${APP_NAME}".pid

SHUTDOWN_MAX_WAIT_SECONDS=10

function killProcess () {
    local pid=$1
    local force=$2
    local maxWaitSeconds=$3
    kill -0 "${pid}"
    if [ $? -eq 0 ]; then
        if [ -n "${force}" ]; then
            kill -9 "${pid}"
        else
            kill "${pid}"
            sleep ${maxWaitSeconds}
            killProcess "${pid}" 1
        fi
    fi
}

function shutdown() {
    local pidFile=$1
    local maxWaitSeconds=$2
    if [ -f "${pidFile}" ];then
        local pid=`cat ${pidFile}`
        killProcess "${pid}" 0 ${maxWaitSeconds}

        rm -f "${pidFile}"
        echo "shutdown success."
    else
        echo "pid file not found, shutdown failed."
        exit 1
    fi
}

shutdown "${PID_FILE}" ${SHUTDOWN_MAX_WAIT_SECONDS}
